using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
namespace Net35.Xrm.Sdk
{
	public sealed class KnownTypesResolver : DataContractResolver
	{
		public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
		{
			Type type = knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null);
			if (type == null)
			{
				string key = KnownTypesProvider.QualifiedName(typeName, typeNamespace);
				Dictionary<string, Type> knownOrganizationRequestResponseTypes = KnownTypesProvider.KnownOrganizationRequestResponseTypes;
				if (knownOrganizationRequestResponseTypes.ContainsKey(key))
				{
					return knownOrganizationRequestResponseTypes[key];
				}
				Dictionary<string, Type> knownCustomValueTypes = KnownTypesProvider.KnownCustomValueTypes;
				if (knownCustomValueTypes != null)
				{
					knownCustomValueTypes.TryGetValue(typeName, out type);
				}
			}
			return type;
		}
		public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
		{
			typeName = null;
			typeNamespace = null;
			if (!knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace))
			{
				typeName = new XmlDictionaryString(XmlDictionary.Empty, type.Name, 0);
				Type type2 = type;
				if (type.IsArray)
				{
					Type elementType = type.GetElementType();
					if (elementType.IsArray)
					{
						elementType = type2.GetElementType();
					}
					type2 = (elementType ?? type);
				}
				string value = string.Empty;
				object[] customAttributes = type2.GetCustomAttributes(typeof(DataContractAttribute), false);
				if (customAttributes != null)
				{
					object[] array = customAttributes;
					int num = 0;
					if (num < array.Length)
					{
						DataContractAttribute dataContractAttribute = (DataContractAttribute)array[num];
						if (!string.IsNullOrEmpty(dataContractAttribute.Namespace))
						{
							value = dataContractAttribute.Namespace;
							typeNamespace = new XmlDictionaryString(XmlDictionary.Empty, value, 0);
						}
					}
				}
				if (typeNamespace == null)
				{
					typeNamespace = new XmlDictionaryString(XmlDictionary.Empty, type.Namespace, 0);
				}
			}
			return true;
		}
	}
}
